<template>
  <a-modal v-model:visible="visible" width="auto" footer="false">
    <template #title>项目管理</template>
    <div id="modal-content">
      <!-- 新增项目表单 -->
      <a-space direction="vertical" style="margin-bottom: 16px; width: 100%">
        <a-input
          v-model="newProjectName"
          placeholder="项目名称（英文/数字/下划线）"
          allow-clear
          :max-length="20"
          @change="validateProjectName"
        >
          <template #suffix>
            <icon-exclamation-circle-fill
              v-if="nameError"
              style="color: var(--color-danger-6); margin-right: 8px"
            />
          </template>
        </a-input>

        <a-input
          v-model="newProjectPath"
          placeholder="输入项目完整路径（包含项目路径，例如：D:/projects）"
          allow-clear
          @change="validateProjectName"
        />

        <a-button
          type="primary"
          @click="createNewProject"
          :disabled="!isFormValid"
          style="width: 100%"
        >
          <template #icon>
            <icon-plus />
          </template>
          新建项目
        </a-button>
      </a-space>
      <a-list>
        <a-list-item v-for="item in projectList" :key="item.id">
          <a-list-item-meta>
            <template #title>
              <a-tooltip :content="item.path">
                <span>{{ item.title }}</span>
              </a-tooltip>
            </template>
          </a-list-item-meta>
          <template #actions>
            <a-button type="text" @click="openProject(item.path, item.title)">打开项目</a-button>
            <a-button type="text" @click="deleteProject(item.path)">删除项目</a-button>
          </template>
        </a-list-item>
      </a-list>
    </div>
    <template #footer>
      <span style="color: var(--color-text-4)">Copyright 2025 Coconut Studio</span>
    </template>
  </a-modal>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { 
  IconExclamationCircleFill,
  IconPlus 
} from '@arco-design/web-vue/es/icon'

const visible = ref(false)
const projectList = ref([])
const newProjectName = ref('')
const newProjectPath = ref('')
const nameError = ref(false)
const isFormValid = ref(false) // 定义 isFormValid

// 验证项目名称和路径
const validateProjectName = () => {
  const isValid = /^[a-zA-Z0-9_]+$/.test(newProjectName.value)
  const isPathValid = newProjectPath.value.length > 3 // 简单路径长度验证
  nameError.value = !isValid
  isFormValid.value = isValid && isPathValid
}

// 获取项目列表数据
async function fetchProjectList() {
  try {
    const response = await fetch('/api/project_list')
    if (response.ok) {
      const data = await response.json()
      projectList.value = data.map((item, index) => ({
        id: index + 1, // 假设API返回的数据没有id字段，这里手动添加一个id
        title: item.title,
        path: item.path // 使用path字段
      }))
    } else {
      console.error('Failed to fetch project list:', response.status)
      Notification.error({
        title: '项目列表获取失败',
        content: `HTTP ${response.status} ${response.statusText}`
      })
    }
  } catch (error) {
    console.error('Error fetching project list:', error)
    Notification.error({
      title: '项目列表获取失败',
      content: error.message
    })
  }
}

// 在组件挂载时获取项目列表
onMounted(fetchProjectList)

function handlePJClick() {
  visible.value = true
  fetchProjectList()
}

function openProject(path, title) {
  console.log(`Opening project at path: ${path}`)
  // 设置localStorage中的当前项目路径，在其他地方读取并打开项目
  localStorage.setItem('currentProjectPath', path)
  localStorage.setItem('currentProjectTitle', title)
  // 设置Cookie
  document.cookie = `currentProjectPath=${path};path=/`
  // 在这里添加打开项目的逻辑，例如跳转到项目路径
  visible.value = false
  Notification.success({
    title: '打开项目成功',
    content: `已打开项目：${title}`
  })
}

async function deleteProject(path) {  // 接收path参数
  try {
    const response = await fetch('/api/delete_project', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'  // 添加请求头
      },
      body: JSON.stringify({ path: path })  // 发送路径参数
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.message === 'success') {
        Notification.success({
          title: '删除成功',
          content: '项目已永久删除'
        })
        await fetchProjectList()
      } else {
        Notification.error({
          title: '删除失败',
          content: result.error || '未知错误'
        })
      }
    } else {
      Notification.error({
        title: '请求失败',
        content: `HTTP ${response.status}`
      })
    }
  } catch (error) {
    Notification.error({
      title: '网络错误',
      content: error.message
    })
  }
}

// 新建项目逻辑
async function createNewProject() {
  if (!isFormValid.value) return

  const saveData = {
    path: newProjectPath.value,
    title: newProjectName.value
  }

  try {
    const response = await fetch('/api/save_project', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(saveData)
    })

    if (response.ok) {
      Notification.success({
        title: '新建成功',
        content: `项目 ${newProjectName.value} 创建成功！`
      })
      newProjectName.value = ''
      newProjectPath.value = ''
      nameError.value = false
      isFormValid.value = false
      fetchProjectList() // 刷新项目列表
    } else {
      console.error('Failed to create project:', response.status)
      Notification.error({
        title: '新建失败',
        content: `HTTP ${response.status} ${response.statusText}`
      })
    }
  } catch (error) {
    console.error('Error creating project:', error)
    Notification.error({
      title: '新建失败',
      content: error.message
    })
  }
}

defineExpose({ handlePJClick })
</script>

<style>
#modal-content {
  -webkit-tap-highlight-color: transparent;
}
</style>